//
//  HWStarRatingView.m
//  OCDome
//
//  Created by 李含文 on 2020/9/4.
//  Copyright © 2020 李含文. All rights reserved.
//

#import "HWStarRatingView.h"


@interface HWStarRatingView ()

@property (nonatomic, strong) UIView *starBackgroundView;
@property (nonatomic, strong) UIView *starForegroundView;


@end
@implementation HWStarRatingView

- (id)initWithFrame:(CGRect)frame {
    return [self initWithFrame:frame numberOfStar:HWDEFAULT_OF_STARS];
}

- (instancetype)init{
    if (self = [super init]) {
        _numberOfStar = HWDEFAULT_OF_STARS;
        [self commonInit];
    }
    return self;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    if (_numberOfStar == 0) {
        _numberOfStar = HWDEFAULT_OF_STARS;
        [self commonInit];
    }
}

- (void)setNumberOfStar:(int)numberOfStar {
    _numberOfStar = numberOfStar;
    [self.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj removeFromSuperview];
    }];
    [self commonInit];
}

- (id)initWithFrame:(CGRect)frame numberOfStar:(int)number {
    self = [super initWithFrame:frame];
    if (self) {
        _numberOfStar = number;
        [self commonInit];
    }
    return self;
}

- (void)commonInit {
    _minNumberOfStar = HWDEFAULT_MIN_OF_STARS;
    _style = HWDEFAULT_STYLE;
    if ([self.subviews containsObject:self.starBackgroundView]) {
        [self.starBackgroundView removeFromSuperview];
    }
    if ([self.subviews containsObject:self.starForegroundView]) {
        [self.starForegroundView removeFromSuperview];
    }
    self.starBackgroundView = [self buidlStarViewWithImageName:HWBACKGROUND_STAR];
    self.starForegroundView = [self buidlStarViewWithImageName:HWFOREGROUND_STAR];
    [self addSubview:self.starBackgroundView];
    [self addSubview:self.starForegroundView];
}

//MARK: - 设置控件分数
- (void)setScore:(float)score withAnimation:(bool)isAnimate {
    [self setScore:score withAnimation:isAnimate completion:^(BOOL finished){}];
}

- (void)setCurrentStar:(float)currentStar {
    _currentStar = currentStar;
    [self setScore:currentStar withAnimation:NO completion:^(BOOL finished){}];
}

- (void)setScore:(float)score
   withAnimation:(bool)isAnimate
      completion:(void (^)(BOOL finished))completion {
    if (score < 0) {
        score = 0;
    }
    if (score > self.numberOfStar) {
        score = self.numberOfStar;
    }
    CGPoint point = CGPointMake(score/self.numberOfStar * self.frame.size.width, 0);
    if(isAnimate){
        __weak __typeof(self)weakSelf = self;
        [UIView animateWithDuration:0.2 animations:^{
            [weakSelf changeStarForegroundViewWithPoint:point];
        } completion:^(BOOL finished){
            if (completion){
                completion(finished);
            }
        }];
    } else {
        [self changeStarForegroundViewWithPoint:point];
    }
}

//MARK: - Touche Event
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    CGPoint point = [touch locationInView:self];
    CGRect rect = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
    if(CGRectContainsPoint(rect,point)){
        [self changeStarForegroundViewWithPoint:point];
    }
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    CGPoint point = [touch locationInView:self];
    __weak __typeof(self)weakSelf = self;
    [UIView animateWithDuration:0.2 animations:^{
        [weakSelf changeStarForegroundViewWithPoint:point];
    }];
}

//MARK: - 通过图片构建星星视图
- (UIView *)buidlStarViewWithImageName:(NSString *)imageName {
    CGRect frame = self.bounds;
    UIView *view = [[UIView alloc] initWithFrame:frame];
    view.clipsToBounds = YES;
    CGFloat spacing = (frame.size.width-(frame.size.height*self.numberOfStar))/(self.numberOfStar-1); // 星星间距
    if (spacing < 0) {
        spacing = 0;
        view.frame = CGRectMake(0, 0, frame.size.height*self.numberOfStar, frame.size.height);
    }
    for (int i = 0; i < self.numberOfStar; i ++){
        UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:imageName]];
        imageView.frame = CGRectMake(i * (frame.size.height+spacing), 0, frame.size.height, frame.size.height);
        [view addSubview:imageView];
    }
    return view;
}


//MARK: - 通过坐标改变前景视图
- (void)changeStarForegroundViewWithPoint:(CGPoint)point {
    CGFloat offset = point.x;
    if (offset < 0){
        offset = 0;
    }
    if (offset < self.frame.size.width/self.numberOfStar*self.minNumberOfStar) {
        offset = self.frame.size.width/self.numberOfStar*self.minNumberOfStar;
    }
    if (offset > self.frame.size.width){
        offset = self.frame.size.width;
    }
    CGFloat realStarScore = offset / (self.bounds.size.width / self.numberOfStar);
    //    向上取整：float ceilf(float);    double ceil(double);
    //    向下取整：float floorf(float);   double floor(double);
    //    四舍五入：float roundf(float);  double round(double);
    switch (self.style) {
        case HWStarStyleWhole:
            _currentStar = ceilf(realStarScore); // 向上取整为
            break;
        case HWStarStyleHalf:
            _currentStar = (roundf(realStarScore)>=realStarScore)?ceilf(realStarScore):(ceilf(realStarScore)-0.5);
            break;
        default:
            _currentStar = [NSString stringWithFormat:@"%.1f", realStarScore].floatValue;
            break;
    }
    CGFloat spacing = (self.frame.size.width-(self.frame.size.height*self.numberOfStar))/(self.numberOfStar-1); // 星星间距
    if (spacing < 0) {
        spacing = 0;
    }
    NSInteger count = _currentStar/1;
    point.x = self.frame.size.height*_currentStar+(count)*spacing;
    self.starForegroundView.frame = CGRectMake(0, 0, point.x, self.frame.size.height);
    _currentStar = [NSString stringWithFormat:@"%0.1f",_currentStar].floatValue;
    if(self.delegate && [self.delegate respondsToSelector:@selector(starRatingView:score:)]){
        [self.delegate starRatingView:self score:_currentStar];
    }
    if (self.completeBlock) {
        self.completeBlock(_currentStar);
    }
}


@end
